package com.connetion_pool.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
  /**
   * @Description 使用C3P0的数据库连接池技术
   */
  // 数据库连接池只需提供一个即可。
  private static ComboPooledDataSource cpds = new ComboPooledDataSource("hellc3p0");
  /**
   * @Description 使用DBCP数据库连接池技术获取数据库连接
   */
  // 创建一个DBCP数据库连接池
  private static DataSource source;
  /** 使用Druid数据库连接池技术 */
  private static DataSource source1;

  static {
    try {
      Properties pros = new Properties();
      InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
      pros.load(is);
      source = BasicDataSourceFactory.createDataSource(pros);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  static {
    try {
      Properties pros = new Properties();
      InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
      pros.load(is);
      source1 = DruidDataSourceFactory.createDataSource(pros);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  // 下面的 getConnection123 分别是 三种连接池技术的获取连接
  public static Connection getConnection1() throws SQLException {
    Connection conn = cpds.getConnection();
    return conn;
  }

  public static Connection getConnection2() throws Exception {
    Connection conn = source.getConnection();
    return conn;
  }

  public static Connection getConnection3() throws SQLException {
    Connection conn = source1.getConnection();
    return conn;
  }

  /**
   * @Description 关闭资源操作
   */
  public static void closeResource(Connection conn, Statement ps) {
    try {
      if (ps != null) ps.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    try {
      if (conn != null) conn.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  /**
   * @Description 使用dbutils.jar中提供的DbUtils工具类，实现资源的关闭
   */
  public static void closeResource1(Connection conn, Statement ps, ResultSet rs) {
    //		try {
    //			DbUtils.close(conn);
    //		} catch (SQLException e) {
    //			e.printStackTrace();
    //		}
    //		try {
    //			DbUtils.close(ps);
    //		} catch (SQLException e) {
    //			e.printStackTrace();
    //		}
    //		try {
    //			DbUtils.close(rs);
    //		} catch (SQLException e) {
    //			e.printStackTrace();
    //		}

    DbUtils.closeQuietly(conn);
    DbUtils.closeQuietly(ps);
    DbUtils.closeQuietly(rs);
  }
}
